package com.yh.hljapp.modules.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.networkbench.agent.impl.NBSAppAgent;
import com.yh.hljapp.AppConfig;
import com.yh.hljapp.AppContext;
import com.yh.hljapp.R;
import com.yh.hljapp.api.ErrorHandler;
import com.yh.hljapp.api.RetrofitSingleton;
import com.yh.hljapp.base.BaseActivity;
import com.yh.hljapp.common.PLog;
import com.yh.hljapp.common.UIHelper;
import com.yh.hljapp.common.UpdateManager;
import com.yh.hljapp.gddb.gbmanager.AddSale_Manager;
import com.yh.hljapp.gddb.gbmanager.MatManager;
import com.yh.hljapp.gddb.gbmanager.ScoreEntryManager;
import com.yh.hljapp.gddb.gdbean.Add_Sync_Bean;
import com.yh.hljapp.gddb.gdbean.MatBean;
import com.yh.hljapp.gddb.gdbean.ScoreEntry;
import com.yh.hljapp.modules.bean.AddSyncBean;
import com.yh.hljapp.modules.bean.CKComp;
import com.yh.hljapp.modules.bean.SimpleBackPage;
import com.yh.hljapp.modules.bean.User;
import com.yh.hljapp.modules.bean.WLBean;
import com.yh.hljapp.modules.widget.dragexpandgrid.CustomGroup;
import com.yh.hljapp.modules.widget.dragexpandgrid.other.DargChildInfo;
import com.yh.hljapp.modules.widget.dragexpandgrid.other.DragIconInfo;

import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.yh.hljapp.AppConfig.SCN_CUST_ACTION_SCODE;

public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener {
    private final String TAG = MainActivity.class.getSimpleName();
    @InjectView(R.id.p3_group)
    CustomGroup p3_group;
    @InjectView(R.id.profile_image)
    ImageView profile_image;
    @InjectView(R.id.tv_username)
    TextView tv_username;
    @InjectView(R.id.tv_userdepartment)
    TextView tv_userdepartment;
    @InjectView(R.id.tv_userduty)
    TextView tv_userduty;
    @InjectView(R.id.tv_user_pay)
    TextView tv_user_pay;
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private Toolbar toolbar;
    private DrawerLayout drawer;
    private FloatingActionButton fab;
    private String userType;
    private ImageView bannner;
    private RelativeLayout headerBackground;
    private ArrayList<CKComp> cmps;

    private long exitTime = 0; ////记录第一次点击的时间

//    private BroadcastReceiver mSamDataReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            if (intent.getAction().equals(SCN_CUST_ACTION_SCODE)) {
//                String message = intent.getStringExtra(AppConfig.SCN_CUST_EX_SCODE);
//                handleOtherText(message);
//            }
//        }
//    };
//
//    private boolean isLoaction = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected boolean hasBackButton() {
        return true;
    }

    @Override
    protected int getActionBarTitle() {
        return R.string.action_settings;
    }

    private ArrayList<DragIconInfo> initAllOriginalInfo() {
        ArrayList<DragIconInfo> iconInfoList = new ArrayList<DragIconInfo>();
        User user = AppContext.getInstance().getCurrentUser();
        if (user != null) {
//            p3_group.setCOLUMNUM(2);
            iconInfoList.add(new DragIconInfo(1, "生成二维码", R.drawable.erw, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
            iconInfoList.add(new DragIconInfo(2, "产品入库", R.drawable.rk, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
            iconInfoList.add(new DragIconInfo(3, "销售出库", R.drawable.ck, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
            iconInfoList.add(new DragIconInfo(4, "退货", R.drawable.th, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
            iconInfoList.add(new DragIconInfo(5, "调拨单", R.drawable.dbd, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
            iconInfoList.add(new DragIconInfo(6, "生产领料", R.drawable.scll, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
            iconInfoList.add(new DragIconInfo(7, "入库列表", R.drawable.rklb, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
            iconInfoList.add(new DragIconInfo(8, "销售出库列表", R.drawable.cklb, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
            iconInfoList.add(new DragIconInfo(9, "退货列表", R.drawable.thlb, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
            iconInfoList.add(new DragIconInfo(10, "合格证列表", R.drawable.thlb, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
        } else {
            Snackbar.make(p3_group, "请重新登录!", Snackbar.LENGTH_SHORT).show();
            this.finish();
        }
        return iconInfoList;
    }


    /**
     * 初始化基础View
     */
    public void initView() {
        User user = AppContext.getInstance().getCurrentUser();
        tv_user_pay.setOnClickListener(this);
        if (user != null) {
            tv_username.setText(user.getName());
//            tv_userdepartment.setText(user.getDepartmentName() + "-" + user.getDuty() + "-" + user.getGXName());
//            tv_userduty.setText(user.getGXName());
            tv_user_pay.setText("当月工资：" + user.getFMonthMoney() + "元");
        } else {
            Snackbar.make(tv_username, "获取用户失败，请重新登录", Snackbar.LENGTH_SHORT).show();
            Intent main = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(main);
            finish();
        }
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        bannner = (ImageView) findViewById(R.id.bannner);
        //标题
        collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
        if (user != null) {
            collapsingToolbarLayout.setTitle(user.getName());
            profile_image.setVisibility(View.GONE);
        }
        //fab
        fab = (FloatingActionButton) findViewById(R.id.fab);
        CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
        final int fabBottomMargin = lp.bottomMargin;
    }

    @Override
    public void initData() {
        NBSAppAgent.setLicenseKey("5a853218974d4b32b0cb77b6fb127256").start(this.getApplicationContext());
        checkUpdate();
        initView();
        initDrawer();
        p3_group.initData(initAllOriginalInfo());
        User mUser = AppContext.getInstance().getCurrentUser();
        if (mUser != null) {
            userType = mUser.getDuty();
        }
        // Register receiver
//        IntentFilter intentFilter = new IntentFilter(SCN_CUST_ACTION_SCODE);
//        registerReceiver(mSamDataReceiver, intentFilter);
    }

    private void checkUpdate() {
//        if (!AppContext.get(AppConfig.KEY_CHECK_UPDATE, true)) {
//            return;
//        }
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                new UpdateManager(MainActivity.this, false).checkUpdate();
            }
        }, 2000);
    }

    /**
     * 初始化抽屉
     */
    private void initDrawer() {
        //https://segmentfault.com/a/1190000004151222
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header_main);
        headerBackground = (RelativeLayout) headerLayout.findViewById(R.id.header_background);
//        if (mSetting.getInt(Setting.HOUR, 0) < 6 || mSetting.getInt(Setting.HOUR, 0) > 18) {
//            //headerBackground.setBackground(this.getResources().getDrawable(R.mipmap.header_back_night)); 过时
//            headerBackground.setBackground(ContextCompat.getDrawable(this, R.mipmap.header_back_night));
//        }
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
                R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
    }

    /**
     * Called when an item in the navigation menu is selected.
     *
     * @param item The selected item
     * @return true to display the item as the selected item
     */
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_about:
                UIHelper.showAboutOSC(this);
                break;
            case R.id.sync_data:
                showWaitDialog();
                RetrofitSingleton.getApiService(MainActivity.this).
                        SyncInfosAll()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(observer);
                break;
            case R.id.change_pwd:
                UIHelper.showSimpleBack(this, SimpleBackPage.CHANGE_PWD, null, "修改密码");
                break;
            case R.id.set_weight:
                UIHelper.showSimpleBack(this, SimpleBackPage.IP_PORT, null, "设置称重");
                break;
            case R.id.set_print:
                UIHelper.showSimpleBack(this, SimpleBackPage.IP, null, "设置打印");
                break;
        }
        drawer.closeDrawer(GravityCompat.START);
        return false;
    }

    //同步数据
    private void initSyncData(AddSyncBean result) {
        List<Add_Sync_Bean> itemList = result.getItemList();
//        List<ScoreEntry> scoreEntryList = result.getScoreEntryList();
//        boolean b1 = ScoreEntryManager.getInstance(this).syncScoreEntry(scoreEntryList);
        boolean b = AddSale_Manager.getInstance(this).insertMatLists(itemList);
        if (b) {
            Snackbar.make(getWindow().getDecorView(), "同步成功！", Snackbar.LENGTH_SHORT).show();
        } else {
            Snackbar.make(getWindow().getDecorView(), "同步失败，或已是最新数据！", Snackbar.LENGTH_SHORT).show();
        }


    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            //super.onBackPressed();
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Snackbar.make(fab, "再按一次退出程序", Snackbar.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_user_pay:
//                UIHelper.showUserPayDetail(this, "工资详情");
                break;
            default:
                break;
        }
    }


    Observer<AddSyncBean> observer = new Observer<AddSyncBean>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            String errBody = ErrorHandler.handle(e);
            Snackbar.make(MainActivity.this.getWindow().getDecorView(), errBody, Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(AddSyncBean result) {
            hideWaitDialog();
            if (result != null) {
                initSyncData(result);
            }
        }
    };
}
